package com.example.demo.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

import tk.mybatis.spring.annotation.MapperScan;

@Configuration
@MapperScan(basePackages = "com.example.demo.mapper", sqlSessionFactoryRef = "pgSqlSessionFactory")
public class DBConfig {

  @Value("${bff.db.url}")
  private String url;

  @Value("${bff.db.username}")
  private String username;

  @Value("${bff.db.password}")
  private String password;
  
  @Bean(name = "pgDataSource")
  public DataSource pgDataSource() {
      DruidDataSource druidDataSource = new DruidDataSource();
      druidDataSource.setDriverClassName("org.postgresql.Driver");
      druidDataSource.setUrl(url);
      druidDataSource.setUsername(username);
      druidDataSource.setPassword(password);
      return druidDataSource;
  }

  @Bean(name = "pgTransactionManager")
  public DataSourceTransactionManager pgTransactionManager() {
      return new DataSourceTransactionManager(pgDataSource());
  }

  @Bean(name = "pgSqlSessionFactory")
  public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("pgDataSource") DataSource pgDataSource) throws Exception {
      final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
      sessionFactory.setDataSource(pgDataSource);
      sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
              .getResources("classpath:mapper/*.xml"));

      org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
      configuration.setMapUnderscoreToCamelCase(true);
      sessionFactory.setConfiguration(configuration);
      return sessionFactory.getObject();
  }

}
